package com.yuji.aacar.widgets.permission;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Process;
import android.support.v4.content.ContextCompat;


public class PermissionsChecker {
    private final Context mContext;

    public PermissionsChecker(Context context) {
        mContext = context.getApplicationContext();
    }

    // 判断运行时权限集合
    public boolean lacksRunTimePermissions(String... permissions) {
        for (String permission : permissions) {
            if (lacksRunTimePermission(permission)) {
                return true;
            }
        }
        return false;
    }

    // 判断运行时是否缺少权限
    private boolean lacksRunTimePermission(String permission) {
        return ContextCompat.checkSelfPermission(mContext, permission) ==
                PackageManager.PERMISSION_DENIED;
    }

    public boolean lacksOpsPermissions(String... permissions) {
        for (String permission : permissions) {
            if (lacksOpsPermission(permission)) {
                return true;
            }
        }
        return false;
    }

    //判断非运行时权限，比如小米安全中心里的权限
    private boolean lacksOpsPermission(String permission) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            AppOpsManager appOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
            int checkOp = appOpsManager.checkOp(permission, Process.myUid(), mContext.getPackageName());
            if (checkOp == AppOpsManager.MODE_IGNORED) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
}
